import axios from 'axios';
import { SaveName, JWT_EXPIRED_ERROR_CODE } from "src/common/const";
import Common from 'src/common/common';
// axios 配置
// axios.defaults.timeout = 5000;
// axios.defaults.baseURL = 'http://localhost:7000';

// http request 拦截器
axios.interceptors.request.use(
    config => {
        //所有接口带上JwtToken
        config.headers[SaveName.JWT_TOKEN_NAME] = localStorage[SaveName.JWT_TOKEN_NAME];

        // console.log("localStorage==>>" + localStorage[SaveName.JWT_TOKEN_NAME]);

        if (typeof (config.data) != 'undefined' && typeof (config.data.TYPE) != 'undefined') {
            if (config.data.TYPE == "FORM") {
                config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                let para = '';
                for (let it in config.data) {
                    para += encodeURIComponent(it) + '=' + encodeURIComponent(config.data[it]) + '&'
                }
                config.data = para;
            }
        }
        return config;
    },
    err => {
        console.log('---------http request err-----------------');
        return Promise.reject(err);
    });

// // http response 拦截器
axios.interceptors.response.use(
    response => {
        // debugger
        if (response.status == '200') {
            //以保存的token
            let loaclToken = localStorage[SaveName.JWT_TOKEN_NAME];
            // console.log("loaclToken==>>" + loaclToken);
            // 拿取服务器返回的JwtToken
            let JwtToken = response.headers[SaveName.JWT_TOKEN_NAME.toLowerCase()];
            // console.log("JwtToken==>>" + JwtToken);
            if (typeof (JwtToken) != 'undefined' && JwtToken != undefined && JwtToken != null && JwtToken.length > 0) {
                if (JwtToken != loaclToken) {
                    //token变化时才覆盖
                    localStorage[SaveName.JWT_TOKEN_NAME] = JwtToken;
                }
            }
            Common.reJwtVal(response.data);//重新获取用户信息，根据jwt的token（适用于jwt失效的情况）


            return response.data;
        }
        return response;
    },
    error => {
        // debugger
        console.log('---------http response error-----------------');
        return Promise.reject(error)
    });

export default axios;